export function download(data, fileName) {
  if (!data) {
    return;
  }
  let url = window.URL.createObjectURL(
    new Blob([data], { type: "application/vnd.ms-excel" })
  );
  let link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", fileName);

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export function formatDate(date, fmt = "YYYY-MM-DD HH:mm:ss") {
  let o = {
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  };
  let week = {
    "0": "\u65e5",
    "1": "\u4e00",
    "2": "\u4e8c",
    "3": "\u4e09",
    "4": "\u56db",
    "5": "\u4e94",
    "6": "\u516d"
  };
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (RegExp.$1.length > 1
        ? RegExp.$1.length > 2
          ? "\u661f\u671f"
          : "\u5468"
        : "") + week[date.getDay() + ""]
    );
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
}

export function getWeekdayByDate(value, splitStr) {
  let weekday = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六"
  ];
  if (value instanceof Date) {
    return weekday[value.getDay()];
  }

  if (typeof value !== "string") return "";

  let arr = value.split(splitStr);
  if (arr.length === 3) {
    return weekday[new Date(arr[0], arr[1], arr[2]).getDay()];
  } else {
    return "";
  }
}

// 百度坐标转换高德坐标
export function baiduToGaode(json) {
  let PJson = { lng: "", lat: "" };
  if (!json || json.length < 2) {
    return PJson;
  }
  let X_PI = (Math.PI * 3000.0) / 180.0;
  let x = json[0] - 0.0065;
  let y = json[1] - 0.006;
  let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
  let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);

  PJson.lng = z * Math.cos(theta);
  PJson.lat = z * Math.sin(theta);
  return PJson;
}
